package com.xwj.rabbitmq.Producter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by xwj on 2017/7/13.
 * ConfirmCallback:用于实现消息发送到RabbitMQ交换器后接收ack回调
 */
@Slf4j
@Component
public abstract class Sender implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    public RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
    }

    public abstract void send(String message);


//    如果消息没有到exchange,则confirm回调,ack=false
//    如果消息到达exchange,则confirm回调,ack=true
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (b)
            log.info("消息发送成功:{}", correlationData != null ? correlationData.toString() : "");
        else
            log.info("消息发送失败:{}", s);
    }


//    exchange到queue成功,则不回调return
//    exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        StringBuilder builder = new StringBuilder();
        builder.append("message:");
        builder.append(message.getBody());
        builder.append("\nreplyCode:");
        builder.append(replyCode);
        builder.append("\nreplyText:");
        builder.append(replyText);
        builder.append("\nexchange:");
        builder.append(exchange);
        builder.append("\nroutingKey:");
        builder.append(routingKey);
        log.info("exchange到queue失败:", builder.toString());
    }
}
